from re import I
import sqlite3
from .database_pool import DatabasePool
from peewee import *
from dto.stock_risk_assessment import RiskAssessmentDTO
from datetime import datetime


class AntRiskAssessmentModel(Model):
    # 股票代码
    stock_code = CharField(max_length=10, unique=True)
    # 上传更新时间
    create_time = DateTimeField(default=datetime.now)
    # 风险描述
    description = TextField()
    # 风险类型 (例如：市场风险、流动性风险)
    risk_type = CharField(max_length=50)
    # 风险等级 (0 - 10 级 ，0级无风险 ，10 级满风险)
    risk_level = IntegerField()
    # 持股建议比例 (百分比)
    stock_hold_ratio = IntegerField()
    # 后期操作
    future_action = CharField(max_length=50)  # 未来操作 (例如：买入、卖出、持有)
    # 匹配标签
    stock_tag_code = CharField(max_length=50)
    # 匹配标签描述
    stock_tag_desc = CharField(max_length=50)
    # 最终总得分
    final_point = IntegerField(null=True)

    class Meta:
        database = DatabasePool(max_connections=5).database  # 指定数据库连接
        table_name = "ant_risk_assessment"  # 指定表名


class RiskAssessmentService:

    # 新增风险评估记录
    def add_risk_assessment(self, risk_info: RiskAssessmentDTO):
        try:
            AntRiskAssessmentModel.create(
                stock_code=risk_info.stock_code,
                description=risk_info.description,
                risk_type=risk_info.risk_type,
                risk_level=risk_info.risk_level,
                stock_hold_ratio=risk_info.stock_hold_ratio,
                future_action=risk_info.future_action,
                stock_tag_code=risk_info.stock_tag_code,
                stock_tag_desc=risk_info.stock_tag_desc,
                final_point=risk_info.final_point,
            )
            AntLogger.info("风险评估记录已添加。")
        except ValueError as ve:
            AntLogger.info(f"字段类型转换错误: {ve}")
        except Exception as e:
            AntLogger.info(f"ant_risk_assessment 新增记录时出错: {e}")

    # 更新风险评估记录
    def update_risk_assessment_by_code(self, risk_info: RiskAssessmentDTO):
        try:
            # 根据股票代码获取现有记录
            risk = AntRiskAssessmentModel.get(
                AntRiskAssessmentModel.stock_code == risk_info.stock_code
            )

            # 更新各字段
            if risk_info.description is not None:
                risk.description = risk_info.description
            if risk_info.risk_type is not None:
                risk.risk_type = risk_info.risk_type
            if risk_info.risk_level is not None:
                risk.risk_level = risk_info.risk_level
            if risk_info.stock_hold_ratio is not None:
                risk.stock_hold_ratio = risk_info.stock_hold_ratio
            if risk_info.future_action is not None:
                risk.future_action = risk_info.future_action
            if risk_info.stock_tag_code is not None:
                risk.stock_tag_code = risk_info.stock_tag_code
            if risk_info.stock_tag_desc is not None:
                risk.stock_tag_desc = risk_info.stock_tag_desc

            # 更新修改时间（如果有的话）
            risk.modified_date = datetime.now()

            # 保存更改
            risk.save()
        except DoesNotExist:
            AntLogger.info(f"未找到股票代码为 {risk_info.stock_code} 的风险评估记录。")

    # 获取所有风险评估记录
    def get_all_risk_assessments(self):
        risks = AntRiskAssessmentModel.select()
        return list(risks)

    # 根据股票代码删除风险评估记录
    def delete_risk_assessment_by_code(self, stock_code):
        try:
            # 查找记录
            risk = AntRiskAssessmentModel.get(
                AntRiskAssessmentModel.stock_code == stock_code
            )
            # 删除记录
            risk.delete_instance()
        except DoesNotExist:
            AntLogger.info(f"未找到股票代码为 {stock_code} 的记录。")

    # 根据股票代码查询风险评估记录
    def get_risk_assessment_by_code(self, stock_code) -> AntRiskAssessmentModel:
        try:
            # 使用 get() 查询单条记录
            risk = AntRiskAssessmentModel.get(
                AntRiskAssessmentModel.stock_code == stock_code
            )
            # 返回查询到的对象
            return risk

        except AntRiskAssessmentModel.DoesNotExist:
            AntLogger.info(f"未找到股票代码为 {stock_code} 的风险评估记录。")
            return None
        except Exception as e:
            AntLogger.info(f"查询时出错: {e}")
            return None
